import sys
import time
import os
from pathlib import Path
import subprocess
from PyQt5.QtCore import QModelIndex, Qt, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QDesktopWidget, QStyleOptionViewItem, QTableWidget, QTableWidgetItem, QWidget, QHBoxLayout, QMenu, QAction, QMessageBox
from qfluentwidgets import TableWidget, MessageBox
from qfluentwidgets import RoundMenu, Action, MenuAnimationType
from qfluentwidgets import FluentIcon as FIF
from Tool.get_network_connections import get_network_connections

class Demo(QWidget):
    def __init__(self):
        super().__init__()
        screen = QDesktopWidget().screenGeometry()
        screenWidth = screen.width() - 150
        screenHeight = screen.height() - 150
        self.resize(screenWidth, screenHeight)

        self.setWindowTitle('网络连接实时查看工具 V1.24.0807')
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move(int((screen.width() - size.width()) / 2), int((screen.height() - size.height()) / 2))

        self.hBoxLayout = QHBoxLayout(self)
        self.tableView = TableWidget(self)
        self.tableView.setBorderVisible(True)
        self.tableView.setWordWrap(False)
        self.setStyleSheet("Demo{background: rgb(255, 255, 255)} ")
        self.hBoxLayout.addWidget(self.tableView)
        self.tableView.setSelectRightClickedRow(True)

        self.TaskWork()
    
    def contextMenuEvent(self, e):
        menu = RoundMenu(parent=self)
        
        action_end = Action(FIF.CLOSE, '结束进程')
        action_end.triggered.connect(self.endProcess)
        menu.addAction(action_end)
        menu.addSeparator()
        
        action_folder = Action(FIF.FOLDER, '打开路径')
        action_folder.triggered.connect(self.startfolder)
        menu.addAction(action_folder)

        menu.exec(e.globalPos(), aniType=MenuAnimationType.DROP_DOWN)

    def endProcess(self):
        selectedRow = self.tableView.currentRow()
        if selectedRow >= 0:
            processNameItem = self.tableView.item(selectedRow, 0)
            processIDItem = self.tableView.item(selectedRow, 1)
            if processNameItem and processIDItem:
                processName = processNameItem.text()
                processID = processIDItem.text()
                
                if processName == "-":
                    w = MessageBox('','这个进程没法结束...',self)
                    w.yesButton.setText('好吧')
                    w.cancelButton.close()
                    if w.exec():
                        pass
                else:
                    title = '警告！'
                    content = f"是否结束进程名 {processName} 进程号: {processID} ？"
                    w = MessageBox(title, content, self)
                    w.yesButton.setText("我很确定")
                    w.cancelButton.setText("取消取消")
                    if w.exec():
                        try:
                            os.kill(int(processID), 9)
                        except Exception as e:
                            pass
    def startfolder(self):
        selectedRow = self.tableView.currentRow()
        if selectedRow >= 0:
            pidItem = self.tableView.item(selectedRow, 1)
            processNameItem = self.tableView.item(selectedRow, 2)
            path_obj = Path(processNameItem.text())
            try:
                if 'C:' in processNameItem.text():
                    工作路径 = os.readlink(f"/proc/{pidItem.text()}/cwd")
                    subprocess.run(['xdg-open', 工作路径])
                else:
                    subprocess.run(['xdg-open', path_obj.parent])
            except Exception as e:
                pass

    def TaskWork(self):
        self.Start = Working()
        self.Start.Task_Log.connect(self.task_finish)
        self.Start.start()

    def task_finish(self, msg):
        sorted_data = dict(sorted(msg.items(), reverse=True))
        network_lists = []
        for values in sorted_data.values():
            for value in values:
                network_lists.append(value)

        self.tableView.setRowCount(len(network_lists))

        for i, network in enumerate(network_lists):
            for j in range(self.tableView.columnCount()):
                self.tableView.setItem(i, j, QTableWidgetItem(str(network[j]).replace('NONE', '').replace('None', '')))

        self.tableView.verticalHeader().hide()
        header_labels = ['进程名', '进程ID', '进程路径', '协议', '本地地址', '远程地址', '状态', '远程地址归属地']
        self.tableView.setColumnCount(len(header_labels))
        self.tableView.setHorizontalHeaderLabels(header_labels)
        for i in range(self.tableView.columnCount()):
            item = QTableWidgetItem(header_labels[i])
            item.setTextAlignment(0x0001)
            self.tableView.setHorizontalHeaderItem(i, item)
        self.tableView.resizeColumnsToContents()
        self.tableView.setSortingEnabled(True)


class Working(QThread):
    Task_Log = pyqtSignal(dict)

    def run(self):
        while True:
            msg = get_network_connections()
            self.Task_Log.emit(msg)

if __name__ == "__main__":
    QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)

    app = QApplication(sys.argv)
    w = Demo()
    w.show()
    sys.exit(app.exec())
